import 'package:flutter/foundation.dart';

/// 全局考试会话状态管理服务
/// 用于跟踪用户是否正在进行考试，防止在考试期间触发自动退出
class ExamSessionService {
  static final ExamSessionService _instance = ExamSessionService._internal();
  factory ExamSessionService() => _instance;
  ExamSessionService._internal();

  // 考试会话状态
  bool _isInExam = false;
  String? _currentExamId;
  String? _currentUserId;
  
  // 状态变化通知
  final ValueNotifier<bool> _examStatusNotifier = ValueNotifier<bool>(false);
  
  /// 获取考试状态通知器
  ValueNotifier<bool> get examStatusNotifier => _examStatusNotifier;
  
  /// 检查是否正在考试中
  bool get isInExam => _isInExam;
  
  /// 获取当前考试ID
  String? get currentExamId => _currentExamId;
  
  /// 获取当前用户ID
  String? get currentUserId => _currentUserId;
  
  /// 开始考试会话
  void startExamSession(String examId, String userId) {
    debugPrint('🎯 开始考试会话: 考试ID=$examId, 用户ID=$userId');
    _isInExam = true;
    _currentExamId = examId;
    _currentUserId = userId;
    _examStatusNotifier.value = true;
  }
  
  /// 结束考试会话
  void endExamSession() {
    debugPrint('🏁 结束考试会话: 考试ID=$_currentExamId, 用户ID=$_currentUserId');
    _isInExam = false;
    _currentExamId = null;
    _currentUserId = null;
    _examStatusNotifier.value = false;
  }
  
  /// 检查指定用户是否正在进行指定考试
  bool isUserInExam(String userId, [String? examId]) {
    if (!_isInExam || _currentUserId != userId) {
      return false;
    }
    
    if (examId != null && _currentExamId != examId) {
      return false;
    }
    
    return true;
  }
  
  /// 重置所有状态（用于调试或异常情况）
  void reset() {
    debugPrint('🔄 重置考试会话状态');
    _isInExam = false;
    _currentExamId = null;
    _currentUserId = null;
    _examStatusNotifier.value = false;
  }
  
  /// 获取当前状态信息（用于调试）
  Map<String, dynamic> getStatusInfo() {
    return {
      'isInExam': _isInExam,
      'currentExamId': _currentExamId,
      'currentUserId': _currentUserId,
    };
  }
}
